using Sirenix.OdinInspector;
using System.Collections.Generic;
using UnityEngine;

namespace Render
{
    [CreateAssetMenu(fileName = "CombineTexture", menuName = "SRC/CombineTexture")]
    public class CombineTexture : ScriptableObject
    {
        [SerializeField]
        List<Texture2D> textures = new List<Texture2D>();
        [SerializeField]
        Vector2Int tileSize;
        [ReadOnly]
        Texture2D combineTex;
        [ReadOnly]
        Vector2Int size;

        public Vector2Int Size { get => size; }
        public Texture2D CombineTex { get => combineTex; }

        public (Vector2 start, Vector2 end) TextureUV(int index)
        {
            int x = index % size.x;
            int y = index / size.x;
            Vector2 start = new Vector2(x / (float)size.x, y / (float)size.y);
            Vector2 end = new Vector2((x + 1) / (float)size.x, (y + 1) / (float)size.y);
            return (start, end);
        }

        public (Vector2Int start, Vector2Int end) TextureIntUV(int index)
        {
            int x = index % size.x;
            int y = index / size.x;
            Vector2Int start = new Vector2Int(x * tileSize.x, y * tileSize.y);
            Vector2Int end = start + tileSize;
            return (start, end);
        }

        [Button]
        public void Combine()
        {
            int count = textures.Count;
            int width = Mathf.RoundToInt(Mathf.Sqrt(count));
            int height = Mathf.CeilToInt(count / (float)width);
            size = new Vector2Int(width, height);

            combineTex = new Texture2D(tileSize.x * width, tileSize.y * height);
            RenderTexture renderTex = RenderTexture.GetTemporary(
                tileSize.x,
                tileSize.y,
                0,
                RenderTextureFormat.Default,
            RenderTextureReadWrite.Linear);

            RenderTexture previous = RenderTexture.active;
            RenderTexture.active = renderTex;

            for (int i = 0; i < textures.Count; i++)
            {
                int x = i % width;
                int y = i / width;
                Graphics.Blit(textures[i], renderTex);
                combineTex.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), x * tileSize.x, y * tileSize.y);
            }
            combineTex.Apply();
            RenderTexture.active = previous;
            RenderTexture.ReleaseTemporary(renderTex);
        }
    }
}